package com.eec.spring;

import com.eec.spring.ioc.BeanDefinition;
import com.eec.spring.ioc.Strategy.scopeStrategy.ScopeStrategy;
import com.eec.spring.ioc.annotation.Component;
import com.eec.spring.ioc.annotation.ComponentScan;
import com.eec.spring.ioc.annotation.Scope;
import com.eec.spring.ioc.springEnum.ScopeType;

import java.io.File;
import java.net.URL;

/**
 * @author LeeC
 * @description
 * @date 2025/7/20
 * @PACKAGE_NAME com.eec.spring
 */
// 启动类
public class ApplicationContent {
    public static String basePackage = "";
    public ApplicationContent(Class<?> appConfig) {
        boolean annotationPresent = appConfig.isAnnotationPresent(ComponentScan.class);
        // com.eec.service
        if (annotationPresent) {
            ComponentScan componentScan = appConfig.getAnnotation(ComponentScan.class);
            basePackage = componentScan.value();
        }
        if(!annotationPresent || "".equals(basePackage)){
            basePackage = appConfig.getPackageName();
        }
        // 扫描ScanPath包下的所有类
        URL resource = ApplicationContent.class.getClassLoader().getResource(basePackage.replace(".", "/"));
        // 获取到文件夹
        File file = new File(resource.getFile());
        ScanFiles(file.listFiles());
    }

    // 组测bena
    public void ScanFiles(File[] files){
        if(files == null || files.length == 0){
            return;
        }
        for (File file : files) {
            if(file.isDirectory()){
                ScanFiles(file.listFiles());
            }
            else if(file.getName().endsWith(".class")){
                try {
                    // 获取到相对 路径 com.eec.service.XXX 全限定名：com.example.MyClass（包名 + 类名，用.分隔）
                    String absolutePath = file.getAbsolutePath();
                    absolutePath = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
                    Class<?> aClass = Class.forName(absolutePath.replace("\\", "."));
                    // 如果需要注册为Bean 则实现Bean的想更换逻辑
                    if(aClass.isAnnotationPresent(Component.class)){
                        // 是否有选择类型
                        boolean annotationPresent = aClass.isAnnotationPresent(Scope.class);
                        BeanDefinition beanDefinition = new BeanDefinition(aClass);
                        // 设置作用域类型
                        if(annotationPresent && aClass.getAnnotation(Scope.class).value() != ScopeType.SINGLETON){
                            beanDefinition.setScope(aClass.getAnnotation(Scope.class).value());
                        }
                        // 这里使用策略模式创建将Bean 进行分类 创建
                        ScopeStrategy.BeanIOC.get(beanDefinition.getScope()).createBean(aClass);
                    }
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }


}
